package resource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import file.XmlFactory;

public class ResourceWriter {
	Document docs;

	public ResourceWriter(Document document) {
		document = docs;
	}

	public void write() {
		File htmlOUT = new File("index.html");
		File jsOUT = new File("index_files/index.js");
		File xmlOUT = new File("index_files/docs.xml");
		File cssOUT = new File("index_files/index.css");
		File dir = new File("index_files");
		dir.mkdir();
		writeXML(new XmlFactory().getXML(), xmlOUT);
		copy(ResourceWriter.class.getResourceAsStream("index.html"), htmlOUT);
		copy(ResourceWriter.class.getResourceAsStream("index.js"), jsOUT);
		copy(ResourceWriter.class.getResourceAsStream("index.css"), cssOUT);
	}

	private void writeXML(Document document, File file) {

		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer;
			writer = new XMLWriter(new FileWriter(file), format);
			writer.write(document);
			writer.close();

			// 紧凑的格式，System.out显示(
//			format = OutputFormat.createCompactFormat();
//			writer = new XMLWriter(System.out, format);
//			writer.write(document);
//			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void copy(InputStream in, File fout) {
		FileOutputStream out = null;
		try {
			try {
				out = new FileOutputStream(fout);
				int n = 0;
				while ((n = in.read()) != -1) {
					out.write(n);
				}
				out.flush();
			} finally {
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
